package com.sky.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.util.UriUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.LinkedHashMap;
import java.util.Map;

@Slf4j
public class GetLocationUtil {

    private static final String URL = "https://api.map.baidu.com/geocoding/v3?";
    private static final String AK = "Yu99wQGlMVQFzVp6NQIhPMLOtiHBwFHd"; // 替换为你的实际AK

    /**
     * 根据地址获取经纬度坐标
     * @param address 地址
     * @return 经纬度字符串，格式：经度,纬度
     */
    public static String getCoordinate(String address) {
        try {
            Map<String, String> params = new LinkedHashMap<>();
            params.put("address", address);
            params.put("output", "json");
            params.put("ak", AK);

            StringBuilder queryString = new StringBuilder();
            queryString.append(URL);
            for (Map.Entry<?, ?> pair : params.entrySet()) {
                queryString.append(pair.getKey()).append("=");
                queryString.append(UriUtils.encode((String) pair.getValue(), "UTF-8")).append("&");
            }

            if (queryString.length() > 0) {
                queryString.deleteCharAt(queryString.length() - 1);
            }

            java.net.URL url = new URL(queryString.toString());
            HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
            httpConnection.setRequestMethod("GET");
            httpConnection.setConnectTimeout(5000);
            httpConnection.setReadTimeout(5000);
            httpConnection.connect();

            InputStreamReader isr = new InputStreamReader(httpConnection.getInputStream());
            BufferedReader reader = new BufferedReader(isr);
            StringBuilder buffer = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            reader.close();
            isr.close();

            // 解析返回的JSON，提取经纬度
            String result = buffer.toString();
            JSONObject jsonObject = JSON.parseObject(result);

            // 检查状态码，0表示成功
            if (jsonObject.getInteger("status") == 0) {
                JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
                Double lng = location.getDouble("lng");
                Double lat = location.getDouble("lat");
                return lng + "," + lat;
            } else {
                log.error("百度地图API返回错误，状态码: {}，地址: {}", jsonObject.getInteger("status"), address);
                return null;
            }
        } catch (Exception e) {
            log.error("获取地理编码失败，地址: {}", address, e);
            return null;
        }
    }

    /**
     * 根据地址获取经纬度对象
     * @param address 地址
     * @return 包含经纬度的数组，[经度, 纬度]
     */
    public static Double[] getCoordinateArray(String address) {
        String coordinate = getCoordinate(address);
        if (coordinate != null && !coordinate.isEmpty()) {
            String[] parts = coordinate.split(",");
            if (parts.length == 2) {
                try {
                    Double lng = Double.parseDouble(parts[0]);
                    Double lat = Double.parseDouble(parts[1]);
                    return new Double[]{lng, lat};
                } catch (NumberFormatException e) {
                    log.error("解析经纬度失败: {}", coordinate, e);
                }
            }
        }
        return null;
    }

  /**
 * 根据经纬度计算两点间距离
 * @param userCoordinate 用户坐标，格式：经度,纬度
 * @param businessCoordinate 商家坐标，格式：经度,纬度
 * @return 距离，单位：米
 */
public static double getDistance(String userCoordinate, String businessCoordinate) {
    try {
        // 解析用户坐标
        String[] userCoords = userCoordinate.split(",");
        double userLng = Double.parseDouble(userCoords[0]);
        double userLat = Double.parseDouble(userCoords[1]);

        // 解析商家坐标
        String[] businessCoords = businessCoordinate.split(",");
        double businessLng = Double.parseDouble(businessCoords[0]);
        double businessLat = Double.parseDouble(businessCoords[1]);

        // 使用Haversine公式计算距离
        return calculateDistance(userLat, userLng, businessLat, businessLng);
    } catch (Exception e) {
        log.error("解析坐标或计算距离失败，用户坐标: {}，商家坐标: {}", userCoordinate, businessCoordinate, e);
        return -1; // 返回-1表示计算失败
    }
}

/**
 * 使用Haversine公式计算两点间距离
 * @param lat1 第一个点的纬度
 * @param lng1 第一个点的经度
 * @param lat2 第二个点的纬度
 * @param lng2 第二个点的经度
 * @return 距离，单位：米
 */
private static double calculateDistance(double lat1, double lng1, double lat2, double lng2) {
    // 地球半径（米）
    final double EARTH_RADIUS = 6371000;

    // 将角度转换为弧度
    double lat1Rad = Math.toRadians(lat1);
    double lat2Rad = Math.toRadians(lat2);
    double deltaLatRad = Math.toRadians(lat2 - lat1);
    double deltaLngRad = Math.toRadians(lng2 - lng1);

    // Haversine公式
    double a = Math.sin(deltaLatRad / 2) * Math.sin(deltaLatRad / 2)
            + Math.cos(lat1Rad) * Math.cos(lat2Rad)
            * Math.sin(deltaLngRad / 2) * Math.sin(deltaLngRad / 2);

    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

    // 计算距离
    return EARTH_RADIUS * c;
}

}
